package org.ainlolcat.ainscience.metaentity;

import org.ainlolcat.ainscience.Controller;
import org.ainlolcat.ainscience.templates.Template;
import org.apache.log4j.Logger;
import org.jdom.Element;

import java.io.IOException;
import java.util.Collection;

/**
 * @author ainlolcat
 *         Date: 10/17/13
 */
public abstract class AbstractMetaEntityParser implements MetaEntityParser{
    private static Logger log = Logger.getLogger(MulticolumnMetaEntityParser.class);
    protected Element desc;
    protected String templateID;
    protected Template template;
    protected String type;         //todo rename to entityType
    protected String name;
    protected Element metaEntityDescription;
    protected String type2reg;
    protected String type2regTemplate;

    public MetaEntity load(Element desc) throws IOException {
        this.desc = desc;
        templateID = desc.getAttributeValue("template");
        type = desc.getAttributeValue("entityType");
        name = desc.getAttributeValue("name");
        log.debug(String.format("Start processing for template: %s entityType: %s name: %s", templateID, type, name));

        //getData Template
        template =  Controller.getInstance().getProject().getTemplateByName(templateID);
        metaEntityDescription = template.getEntityParseParams(type);
        type2reg = metaEntityDescription.getChild("type2reg").getAttributeValue("name");
        type2regTemplate = metaEntityDescription.getChild("type2reg").getAttributeValue("template");
        if (type2regTemplate == null)
            type2regTemplate = template.getName();
        return loadInternal();
    }

    protected Element prepareEntityDefinition(String basename, int currentNum, String type2reg, String type2regTemplate, Collection<Element> children){
        return prepareEntityDefinition(basename + String.format("%1$03d",currentNum), type2reg, type2regTemplate, children);
    }

    protected Element prepareEntityDefinition(String name, String type2reg, String type2regTemplate, Collection<Element> children){
        Element e = new Element("entity_def") ;
        e.setAttribute("name", name);
        e.setAttribute("entityType",type2reg);
        e.setAttribute("templateName",type2regTemplate);
        for (Object child:children){
            Element clone = (Element) ((Element)child).clone();
            clone.detach();
            e.addContent(clone);
        }
        return e;
    }

    protected abstract MetaEntity loadInternal() throws IOException;

    protected abstract int loadInternalFromFile(String filename) throws IOException;
}
